package com.ruoyi.xqsp.controller;


import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.xqsp.constant.ZhiFuBaoPost;
import com.ruoyi.xqsp.domain.SpRechargeRecord;
import com.ruoyi.xqsp.domain.SpWxpay;
import com.ruoyi.xqsp.domain.entity.ReceivePay;
import com.ruoyi.xqsp.domain.entity.ZhiFuBao;
import com.ruoyi.xqsp.service.*;
import com.ruoyi.xqsp.utils.Md5;
import com.ruoyi.xqsp.utils.XqidUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/xqsp/zhifubao")
public class ZhiFuBaoController {

    @Autowired
    private ISpUsersService spUsersService;
    @Autowired
    private ISpRechargeRecordService spRechargeRecordService;
    @Autowired
    private ISpGlodMoneyService spGlodMoneyService;
    @Autowired
    private ISpMemberMoneyService spMemberMoneyService;
    @Autowired
    private ISpWxpayService spWxpayService;
    /**
     * 支付宝支付
     * @param zhiFuBao
     * @return
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("/aliPay")
    public AjaxResult aliPay(@RequestBody ZhiFuBao zhiFuBao) throws NoSuchAlgorithmException {

        SpRechargeRecord spRechargeRecord=new SpRechargeRecord();
        spRechargeRecord.setUserId(zhiFuBao.getUserId());
        spRechargeRecord.setRechargeRecordType(zhiFuBao.getRechargeRecordType());
        spRechargeRecord.setRechargeRecordOrder(XqidUtils.generateOrderId());
        spRechargeRecord.setRechargeRecordTime(new Date());
        spRechargeRecord.setRechargeRecordState(1);
        if (zhiFuBao.getType() == 1) {
            spRechargeRecord.setRechargeRecordMoney(spMemberMoneyService.selectSpMemberMoneyById(Long.valueOf(zhiFuBao.getMoneyType())).getMemberMoneyNumber());
        }
        if (zhiFuBao.getType() == 2){
            spRechargeRecord.setRechargeRecordMoney(spGlodMoneyService.selectSpGlodMoneyById(Long.valueOf(zhiFuBao.getMoneyType())).getGlodMoneyNumber());
        }
        spRechargeRecordService.insertSpRechargeRecord(spRechargeRecord);//向充值记录表中添加数据


        SpWxpay spWxpay=spWxpayService.selectSpWxpayById(1l);


        String AuthorizationURL = spWxpay.getMchId();//网关地址
        String merchantId = spWxpay.getAppId();//商户号
        String keyValue = spWxpay.getSpKey() ;//
        //String Channelid=zhiFuBao.getChannelid() ;//
        String  Moneys    = String.valueOf(spRechargeRecord.getRechargeRecordMoney());  //金额request.getParameter("Moneys")
        String     pay_bankcode=null;
        if(zhiFuBao.getChannelid()==1){
            pay_bankcode="902";   //'银行编码
        }else if(zhiFuBao.getChannelid()==2){
            pay_bankcode="903";   //'银行编码
        }
        String    pay_memberid=merchantId;//商户id
        String    pay_orderid= spRechargeRecord.getRechargeRecordOrder();//20位订单号 时间戳+6位随机字符串组成
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String    pay_applydate=sdf.format(new Date());//yyyy-MM-dd HH:mm:ss
        String    pay_notifyurl="http://localhost:8080/aliPay/notify";//通知地址 http://"+request.getRequestURI()+"/Pay/notifyurl.asp
        String    pay_callbackurl="http://localhost:8080/aliPay/callback";//回调地址 http://"+request.getRequestURI()+"/Pay/Callback.asp
        String    pay_amount=Moneys;
        //String    pay_attach="";
        String    pay_productname=zhiFuBao.getPay_productname();
        //String    pay_productnum="";
        //String    pay_productdesc="";
        //String    pay_producturl="";
        String stringSignTemp="pay_amount="+pay_amount+"&pay_applydate="+pay_applydate+"&pay_bankcode="+pay_bankcode+"&pay_callbackurl="+pay_callbackurl+"&pay_memberid="+pay_memberid+"&pay_notifyurl="+pay_notifyurl+"&pay_orderid="+pay_orderid+"&key="+keyValue+"";
        String pay_md5sign= Md5.md5(stringSignTemp).toUpperCase();

        System.out.println(stringSignTemp);
        System.out.println(pay_md5sign);
        JSONObject object=new JSONObject();
        object.put("pay_memberid",pay_memberid);
        object.put("pay_orderid",pay_orderid);
        object.put("pay_applydate",pay_applydate);
        object.put("pay_bankcode",pay_bankcode);
        object.put("pay_notifyurl",pay_notifyurl);
        object.put("pay_callbackurl",pay_callbackurl);
        object.put("pay_amount",pay_amount);
        object.put("pay_productname",pay_productname);
        object.put("pay_memberid",pay_memberid);
        object.put("pay_md5sign",pay_md5sign);
        String result= ZhiFuBaoPost.sendPost(AuthorizationURL,object);

        System.out.println(result);
        return AjaxResult.success(result);
    }


    @PostMapping("/receive")
    public AjaxResult receive(){
        String AuthorizationURL ="http://www.ddq800.cn/Pay_Trade_query.html";
        String pay_memberid="210609028";
        String pay_orderid="20210628211137709886";
        String pay_md5sign="pay_amount=50&pay_applydate=2021-06-28 21:11:37&pay_bankcode=902&pay_callbackurl=http://localhost:8080/aliPay/callback&pay_memberid=210609028&pay_notifyurl=http://localhost:8080/aliPay/notify&pay_orderid=20210628211137709886&key=m529c0aflgfb12gymxjth5w32ynazn6p";
        JSONObject object=new JSONObject();
        object.put("pay_memberid",pay_memberid);
        object.put("pay_orderid",pay_orderid);
        object.put("pay_md5sign",pay_md5sign);
        String result= ZhiFuBaoPost.sendPost(AuthorizationURL,object);
        System.out.println(result);
        return AjaxResult.success(result);
    }


    /**
     * 回调
     * @param receivePay
     * @return
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("/notify")
    public AjaxResult notify(@RequestBody ReceivePay receivePay)throws NoSuchAlgorithmException{
        SpWxpay spWxpay=spWxpayService.selectSpWxpayById(1l);
        String memberid=receivePay.getMemberid();
        String orderid=receivePay.getOrderid();
        String amount=receivePay.getAmount();
        String datetime=receivePay.getDatetime();
        String returncode=receivePay.getReturncode();
        String transaction_id=receivePay.getTransaction_id();
        String attach=receivePay.getAttach();
        String keyValue=spWxpay.getSpKey();
        String sign=receivePay.getSign();
        String SignTemp="amount="+amount+"+datetime="+datetime+"+memberid="+memberid+"+orderid="+orderid+"+returncode="+returncode+"+transaction_id="+transaction_id+"+key="+keyValue+"";
        String md5sign= Md5.md5(SignTemp);//MD5加密
        if (sign.equals(md5sign)){
            if(returncode.equals("00")){
                //支付成功，写返回数据逻辑
                return AjaxResult.success("ok");
            }else{

                return AjaxResult.error1("支付失败222");
            }
        }else{
            return AjaxResult.error2("验签失败333");
        }
    }
    /**
     * 回调
     * @param receivePay
     * @return
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("/callback")
    public AjaxResult callback(@RequestBody ReceivePay receivePay)throws NoSuchAlgorithmException{
        SpWxpay spWxpay=spWxpayService.selectSpWxpayById(1l);
        String memberid=receivePay.getMemberid();
        String orderid=receivePay.getOrderid();
        String amount=receivePay.getAmount();
        String datetime=receivePay.getDatetime();
        String returncode=receivePay.getReturncode();
        String transaction_id=receivePay.getTransaction_id();
        String attach=receivePay.getAttach();
        String sign=receivePay.getSign();
        String keyValue=spWxpay.getSpKey();
        String SignTemp="amount="+amount+"+datetime="+datetime+"+memberid="+memberid+"+orderid="+orderid+"+returncode="+returncode+"+transaction_id="+transaction_id+"+key="+keyValue+"";
        String md5sign= Md5.md5(SignTemp);//MD5加密
        if (sign.equals(md5sign)){
            if(returncode.equals("00")){
                //支付成功，写返回数据逻辑
                String rechargeRecordOrder = receivePay.getOrderid();
                SpRechargeRecord spRechargeRecord = spRechargeRecordService.selectSpRechargeRecordByOrder(rechargeRecordOrder);
                Long days;
                if (spRechargeRecord.getRechargeRecordType() == 1) {//VIP月卡
                    days = 30l;
                    spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
                    spRechargeRecord.setRechargeRecordState(1);
                    spRechargeRecordService.updateSpRechargeRecord(spRechargeRecord);
                }
                if (spRechargeRecord.getRechargeRecordType() == 2) {//VIP季卡
                    days = 90l;
                    spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
                    spRechargeRecord.setRechargeRecordState(1);
                    spRechargeRecordService.updateSpRechargeRecord(spRechargeRecord);
                }
                if (spRechargeRecord.getRechargeRecordType() == 8) {//VIP半年卡
                    days = 180l;
                    spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
                    spRechargeRecord.setRechargeRecordState(1);
                    spRechargeRecordService.updateSpRechargeRecord(spRechargeRecord);
                }
                if (spRechargeRecord.getRechargeRecordType() == 3) {//VIP年卡
                    days = 360l;
                    spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
                    spRechargeRecord.setRechargeRecordState(1);
                    spRechargeRecordService.updateSpRechargeRecord(spRechargeRecord);
                }
                if (spRechargeRecord.getRechargeRecordType() == 7) {//金币充值
                    Long glod = spRechargeRecord.getRechargeRecordMoney();
                    spUsersService.updatGlodByUserId(spRechargeRecord.getUserId(), glod);
                    spRechargeRecord.setRechargeRecordState(1);
                    spRechargeRecordService.updateSpRechargeRecord(spRechargeRecord);
                }

                return AjaxResult.success("ok");
            }else{

                return AjaxResult.error1("支付失败222");
            }
        }else{
            return AjaxResult.error2("验签失败333");
        }
    }

}
